<template>
  <q-page padding class="login-container">
    <!-- 已登录状态 -->
    <q-card v-if="isLoggedIn" class="login-box logged-in">
      <div class="text-h6 text-center q-mb-lg">欢迎使用</div>

      <div class="text-center q-mb-lg">
        <q-icon name="check_circle" color="positive" size="48px" />
        <div class="text-h6 q-mt-md">您已登录</div>
        <div class="text-subtitle2 q-mt-sm">
          可以使用本系统的所有功能
        </div>
      </div>

      <div class="row justify-center q-mt-lg">
        <q-btn
          label="返回首页"
          color="primary"
          class="q-mr-md"
          @click="goToHome"
        />
        <q-btn
          label="退出登录"
          color="negative"
          outline
          @click="confirmLogout"
        />
      </div>
    </q-card>

    <!-- 未登录状态 - 原有的登录表单 -->
    <q-card v-else class="login-box">
      <div class="text-h6 text-center q-mb-md">统计分析平台</div>

      <q-tabs
        v-model="activeTab"
        class="text-grey-8 q-mb-sm"
        align="justify"
        active-color="primary"
        indicator-color="primary"
        dense
        narrow-indicator
      >
        <q-tab name="account" label="账号密码登录" />
        <q-tab name="phone" label="手机号登录" />
      </q-tabs>

      <q-tab-panels v-model="activeTab" animated>
        <!-- 账号密码登录 -->
        <q-tab-panel name="account" class="q-pa-none">
          <q-form @submit="onSubmit" class="login-form">
            <q-input
              v-model="username"
              dense
              outlined
              clearable
              label="邮箱/账号名/8位ID"
              class="q-mb-sm"
              :rules="[val => !!val || '请输入账号']"
            >
              <template v-slot:prepend>
                <q-icon name="person" size="sm" />
              </template>
            </q-input>

            <q-input
              v-model="password"
              dense
              outlined
              :type="isPwd ? 'password' : 'text'"
              label="登录密码"
              class="q-mb-sm"
              :rules="[val => !!val || '请输入密码']"
            >
              <template v-slot:prepend>
                <q-icon name="lock" size="sm" />
              </template>
              <template v-slot:append>
                <q-icon
                  :name="isPwd ? 'visibility_off' : 'visibility'"
                  class="cursor-pointer"
                  @click="isPwd = !isPwd"
                  size="sm"
                />
              </template>
            </q-input>

            <div class="row items-center q-mb-sm">
              <q-checkbox v-model="agreement" dense label="我已阅读并同意" />
              <q-btn flat dense color="primary" label="用户协议" @click="showAgreement = true" />
            </div>

            <q-btn
              label="登 录"
              color="primary"
              class="full-width"
              :loading="loading"
              :disable="!agreement"
              @click="onSubmit"
            />
          </q-form>
        </q-tab-panel>

        <!-- 手机号登录 -->
        <q-tab-panel name="phone" class="q-pa-none">
          <q-form @submit="onPhoneLogin" class="login-form">
            <q-input
              v-model="phone"
              dense
              outlined
              clearable
              label="手机号"
              class="q-mb-sm"
              :rules="[
                val => !!val || '请输入手机号',
                val => /^1[3-9]\d{9}$/.test(val) || '请输入正确的手机号'
              ]"
            >
              <template v-slot:prepend>
                <q-icon name="phone" size="sm" />
              </template>
            </q-input>

            <div class="row q-mb-sm">
              <q-input
                v-model="verificationCode"
                dense
                outlined
                label="验证码"
                class="col-8"
                :rules="[val => !!val || '请输入验证码']"
              >
                <template v-slot:prepend>
                  <q-icon name="key" size="sm" />
                </template>
              </q-input>
              <q-btn
                :disable="isCodeSent"
                color="primary"
                flat
                class="col-4"
                @click="onSendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}s` : "获取验证码" }}
              </q-btn>
            </div>

            <div class="row items-center q-mb-sm">
              <q-checkbox v-model="agreement" dense label="我已阅读并同意" />
              <q-btn flat dense color="primary" label="用户协议" @click="showAgreement = true" />
            </div>

            <q-btn
              label="登 录"
              color="primary"
              class="full-width"
              :loading="loading"
              :disable="!agreement"
              @click="onPhoneLogin"
            />
          </q-form>
        </q-tab-panel>
      </q-tab-panels>

      <div class="text-center q-mt-sm">
        <q-btn
          flat
          color="primary"
          label="前往统计帮帮帮平台注册"
          size="sm"
          @click="showRegistrationDialog = true"
        />
      </div>
    </q-card>

    <!-- 用户协议对话框 -->
    <q-dialog v-model="showAgreement">
      <q-card style="width: 600px; max-width: 80vw;">
        <q-card-section class="row items-center">
          <div class="text-h6">用户协议</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="scroll" style="max-height: 50vh;">
          <p>用户协议内容...</p>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 注册引导弹窗 -->
    <q-dialog v-model="showRegistrationDialog">
      <q-card style="min-width: 300px">
        <q-card-section class="row items-center">
          <div class="text-h6">前往注册</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="q-pt-none">
          <p>请前往统计帮帮帮官方平台注册账号：</p>
          <div class="text-center q-py-md">
            <a
              href="https://www.tjbbb.com/login"
              target="_blank"
              class="official-link"
            >
              <q-btn
                color="primary"
                label="访问官方平台"
                icon="launch"
              />
            </a>
          </div>
          <p class="text-caption text-grey">注册完成后可使用新账号登录本平台</p>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 退出确认对话框 -->
    <q-dialog v-model="showLogoutConfirm" persistent>
      <q-card style="min-width: 300px">
        <q-card-section class="row items-center">
          <q-avatar icon="logout" color="negative" text-color="white" />
          <span class="q-ml-sm">确定要退出登录吗？</span>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="确定" color="negative" @click="handleLogout" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { login, getPhoneCode, loginUserWithPhone } from 'src/api/user';

const router = useRouter();
const $q = useQuasar();

const username = ref("");
const password = ref("");
const phone = ref("");
const verificationCode = ref("");
const loading = ref(false);
const countdown = ref(0);
const isCodeSent = ref(false);
const agreement = ref(false);
const activeTab = ref("account");
const isPwd = ref(true);
const showAgreement = ref(false);
const showRegistrationDialog = ref(false);
const showLogoutConfirm = ref(false);

let countdownTimer;

// 登录状态
const isLoggedIn = ref(false);

// 在组件挂载时检查登录状态
onMounted(() => {
  checkLoginStatus();
});

// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('token');
  isLoggedIn.value = !!token;
};

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 显示退出确认对话框
const confirmLogout = () => {
  showLogoutConfirm.value = true;
};

// 处理退出登录
const handleLogout = () => {
  // 清除本地存储的token和用户信息
  localStorage.removeItem('token');
  localStorage.removeItem('userId');

  // 更新登录状态
  isLoggedIn.value = false;

  // 显示退出成功提示
  $q.notify({
    type: 'positive',
    message: '已成功退出登录'
  });
};

const onSubmit = async () => {
  if (!username.value || !password.value) {
    $q.notify({
      type: 'warning',
      message: '请填写完整信息'
    });
    return;
  }

  loading.value = true;
  try {
    const res = await login({
      username: username.value,
      password: password.value
    });

    if (res.code === 200) {
      $q.notify({
        type: 'positive',
        message: '登录成功'
      });
      // 存储用户信息
      localStorage.setItem('token', res.token);
      localStorage.setItem('userId', res.userId);
      // 跳转到首页
      router.push('/');
    } else {
      $q.notify({
        type: 'negative',
        message: res.message || '登录失败'
      });
    }
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: error.message || '登录失败，请稍后重试'
    });
  } finally {
    loading.value = false;
  }
};

const onPhoneLogin = async () => {
  if (!agreement.value) {
    $q.notify({
      type: 'warning',
      message: '请先同意用户协议'
    });
    return;
  }

  if (!phone.value || !verificationCode.value) {
    $q.notify({
      type: 'warning',
      message: '请填写完整信息'
    });
    return;
  }

  loading.value = true;
  try {
    const res = await loginUserWithPhone({
      phone: phone.value,
      code: verificationCode.value
    });

    if (res.code === 200) {
      $q.notify({
        type: 'positive',
        message: '登录成功'
      });
      localStorage.setItem('token', res.token);
      localStorage.setItem('userId', res.userId);
      router.push('/');
    } else {
      $q.notify({
        type: 'negative',
        message: res.message || '登录失败'
      });
    }
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: error.message || '登录失败，请稍后重试'
    });
  } finally {
    loading.value = false;
  }
};

const onSendVerificationCode = async () => {
  if (!phone.value || !/^1[3-9]\d{9}$/.test(phone.value)) {
    $q.notify({
      type: 'warning',
      message: '请输入正确的手机号'
    });
    return;
  }

  try {
    const res = await getPhoneCode({
      phone: phone.value
    });

    if (res.code === 200) {
      countdown.value = 60;
      isCodeSent.value = true;

      countdownTimer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--;
        } else {
          clearInterval(countdownTimer);
          isCodeSent.value = false;
        }
      }, 1000);

      $q.notify({
        type: 'positive',
        message: '验证码已发送'
      });
    } else {
      $q.notify({
        type: 'negative',
        message: res.message || '验证码发送失败'
      });
    }
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: error.message || '验证码发送失败'
    });
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 360px;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
}

.login-form {
  min-height: 180px;
}

:deep(.q-field) {
  height: 40px !important;
  cursor: text;
}

:deep(.q-field__control) {
  height: 40px !important;
  cursor: text;
  padding: 0 8px;
}

:deep(.q-field__native) {
  padding: 0;
  cursor: text;
  min-height: 40px !important;
}

:deep(.q-field__control-container) {
  cursor: text;
  height: 100%;
  padding: 0;
}

:deep(.q-field__prepend) {
  height: 40px;
  padding: 0 8px;
  display: flex;
  align-items: center;
}

:deep(.q-field__append) {
  height: 40px;
  padding: 0 8px;
  display: flex;
  align-items: center;
}

:deep(.q-field--disabled) {
  opacity: 1;
  cursor: not-allowed;
}

:deep(.q-field:before),
:deep(.q-field:after) {
  display: none;
}

:deep(.q-field:hover) {
  border-color: #1976d2;
}

:deep(.q-field--focused) {
  border-color: #1976d2;
}

:deep(.q-field__label) {
  pointer-events: none;
  z-index: 1;
}

.q-btn {
  height: 38px;
}

/* 按钮悬停效果 */
.q-btn:not(.disabled):hover {
  opacity: 0.9;
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

.official-link {
  text-decoration: none;
}

/* 添加新的样式 */
.text-subtitle2 {
  color: #666;
}

.q-avatar {
  font-size: 24px;
}

/* 登录状态卡片的特殊样式 */
.login-box.logged-in {
  text-align: center;
  padding: 40px;
}

/* 动画效果 */
.q-icon {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
